package io.github.topcatv.mall.model.sys.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.collect.Sets;
import io.github.topcatv.mall.common.exception.BizErrorEnum;
import io.github.topcatv.mall.common.exception.BizException;
import io.github.topcatv.mall.common.security.jwt.JwtTokenUtil;
import io.github.topcatv.mall.model.sys.entity.User;
import io.github.topcatv.mall.model.sys.entity.UserRole;
import io.github.topcatv.mall.model.sys.mapper.UserMapper;
import io.github.topcatv.mall.model.sys.service.IUserRoleService;
import io.github.topcatv.mall.model.sys.service.IUserService;
import org.apache.commons.lang3.ArrayUtils;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Collection;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author liuyi
 * @since 2019-10-14
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    @Resource
    private JwtTokenUtil jwtTokenUtil;

    @Resource
    private PasswordEncoder passwordEncoder;

    @Resource
    private IUserRoleService userRoleService;

    @Override
    public String refreshToken(String oldToken) {
        if (!jwtTokenUtil.isTokenExpired(oldToken)) {
            return jwtTokenUtil.refreshToken(oldToken);
        }
        return "";
    }

    @Override
    public Integer registryUser(String username, String password, String mobile) {
        User user = new User();
        user.setCredentialsExpired(false);
        user.setLocked(false);
        user.setMobile(mobile);
        user.setPwd(passwordEncoder.encode(password));
        user.setDeleted(false);
        user.setUsername(username);
        try {
            baseMapper.insert(user);
            return user.getId();
        } catch (DuplicateKeyException e) {
            throw new BizException(BizErrorEnum.USER_EXIST, e);
        }
    }

    @Override
    public void addRoles(Integer id, Integer[] roleIds) {
        QueryWrapper<UserRole> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(UserRole::getUserId, id);
        userRoleService.remove(queryWrapper);
        Collection<UserRole> userRoles = Sets.newHashSet();
        if (ArrayUtils.isNotEmpty(roleIds)) {
            for (Integer roleId : roleIds) {
                UserRole userRole = new UserRole();
                userRole.setUserId(id);
                userRole.setRoleId(roleId);
                userRoles.add(userRole);
            }
        }
        userRoleService.saveBatch(userRoles);
    }
}
